"ui";

importClass(android.view.View);
var addJs = require("./add.js");
var themeJs = require("./theme.js");
var networkSourceJs = require("./networkSource.js");

dialogs.setDefaultDialogType("app");

var inAndOut = {};

let selectView = ui.inflate(
    <vertical padding="16 0">
        <text textColor="{{themeJs.text2}}" text="        目前仅支持导出为简单词本专用的(.45qq)文件，以后将支持导出更多类型。" marginBottom="10"/>
        <text textColor="{{themeJs.text2}}">工作区</text>
        <list id="workList" h="*" marginBottom="10" layout_weight="1">
            <vertical>
                <horizontal id="item" padding="5 10" gravity="center_vertical" w="*" h="auto" foreground="?selectableItemBackground">
                    <text id="title" layout_weight="1" text="{{this.title}}" ellipsize="end" textColor="#222222" textSize="16" maxLines="1" />
                    <checkbox id="done" marginLeft="4" marginRight="6" checked="{{this.done}}" />
                </horizontal>
                <View w="*" h="1" bg="#bbbbbb" marginLeft="10" marginRight="10"/>
            </vertical>
        </list>
        <text textColor="{{themeJs.text2}}">导出名字</text>
        <input id="name" textColor="{{themeJs.text}}"/>
    </vertical>, null, false);

selectView.workList.on("item_bind", function(itemView, itemHolder) {
    itemView.done.on("check", function(checked) {
        itemHolder.item.done = checked;
        if (checked && selectView.name.text() == "") {
            selectView.name.setText(itemHolder.item.title);
            next = false;
        }
    });
});

selectView.workList.on("item_click", function(item, i, itemView, listView) {
    itemView.done.checked = !itemView.done.checked;
});

// 显示对话框
var outDialogs = dialogs.build({
    customView: selectView,
    title: "选择要导出的工作区",
    titleColor: themeJs.text,
    positive: "导出",
    neutral: "分享",
    negative: "取消",
    wrapInScrollView: false,
    autoDismiss: true
}).on("neutral", (dialog) => {
    if (getCheckCount() == 0) {
        toast("选择内容不能为空！");
        return;
    }
    let name = selectView.name.text();
    files.removeDir("./share/");
    files.createWithDirs("./share/");
    files.write("./share/" + name + ".45qq", getListJson());
    var i = app.intent({
        action: "SEND",
        type: "text/plain",
        flags: ["activity_new_task"],
        extras: {
            "android.intent.extra.STREAM": app.getUriForFile(files.path("./share/" + name + ".45qq")),
        },
    });
    i = Intent.createChooser(i, "来自简单词本的分享");
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    context.startActivity(i);
}).on("positive", (dialog) => {
    if (getCheckCount() == 0) {
        toast("选择内容不能为空！");
        return;
    }
    files.ensureDir("/sdcard/简单词本/export/");
    let path = "/sdcard/简单词本/export/" + selectView.name.text() + ".45qq";
    if (files.exists(path)) {
        let sameDialogs = dialogs.build({
            title: "存在同名文件",
            content: "请选择接下来的操作",
            titleColor: themeJs.text,
            positive: "替换",
            neutral: "取消",
            negative: "保留两个文件",
            wrapInScrollView: false,
            autoDismiss: true
        }).on("positive", (dialog) => {
            files.write(path, getListJson());
            confirm("导出成功！", "导出路径：" + path);
        }).on("negative", (dialog) => {
            let paths = "";
            for (let i = 1; files.exists(paths); i++) {
                paths = "/sdcard/简单词本/export/" + selectView.name.text() + "(" + i + ").45qq";
            }
            files.write(paths, getListJson());
            confirm("导出成功！", "导出路径：" + paths);
        });
        sameDialogs.getView().attr("bg", themeJs.layout);
        sameDialogs.show();
    } else {
        files.write(path, getListJson());
        confirm("导出成功！", "导出路径：" + path);
    }
});

selectView.getParent().getParent().attr("bg", themeJs.layout);

let inView = ui.inflate(
    <vertical padding="16 0">
        <text textColor="{{themeJs.text2}}" text="        目前仅支持导入由简单词本导出的(.45qq)文件，以后将支持更多类型。" marginBottom="10"/>
        <text textColor="{{themeJs.text2}}">文件</text>
        <frame layout_weight="1">
            <text id="prompt" textColor="{{themeJs.text2}}" h="*" margin="20" gravity="center">这里会自动扫描QQ、微信和单词本
                分享目录下的文件
            </text>
            <list id="workList" h="*" minHeight="30" marginBottom="10">
                <vertical id="item">
                    <horizontal padding="5 10" foreground="?selectableItemBackground">
                        <card cardCornerRadius="24dp" w="48" h="48">
                            <vertical w="*" h="*" gravity="center" bg="#795547">
                                <img src="@drawable/ic_description_black_48dp" tint="#ffffff" w="24" h="*"/>
                            </vertical>
                        </card>
                        <vertical w="*" marginLeft="10">
                            <horizontal gravity="center_vertical" w="*" h="auto" layout_weight="2">
                                <text id="name" layout_weight="1" text="{{this.name}}" ellipsize="end" textColor="#222222" textSize="16" maxLines="1" />
                                <text text="{{'来自' + this.from}}"/>
                            </horizontal>
                            <text text="{{this.content}}" textSize="12" maxLines="2" ellipsize="end" layout_weight="1"/>
                        </vertical>
                    </horizontal>
                    <View w="*" h="1" bg="#bbbbbb" marginLeft="10" marginRight="10"/>
                </vertical>
            </list>
        </frame>
        <text textColor="{{themeJs.text2}}">路径</text>
        <input id="path" textColor="{{themeJs.text}}"/>
    </vertical>, null, false);

inView.workList.on("item_click", function(item, i, itemView, listView) {
    inView.path.setText(item.path);
});

var inDialogs = dialogs.build({
    customView: inView,
    title: "选择要导入的文件",
    titleColor: themeJs.text,
    positive: "导入",
    negative: "取消",
    wrapInScrollView: false,
    autoDismiss: false
}).on("positive", (dialog) => {
    if (inAndOut.in45qqFromPath(inView.path.text()))
        dialog.dismiss();
}).on("negative", (dialog) => {
    dialog.dismiss();
});

inView.getParent().getParent().attr("bg", themeJs.layout);

function getCheckCount() {
    let c = 0;
    for (let i in workList)
        if (workList[i].done)
            c++;
    return c;
}

function getListJson() {
    let str = {};
    let word;
    for (let i in workList) {
        word = workList[i];
        if (word.done) {
            let lw = str[word.title] = {};
            lw.summary = word.summary;
            let content = lw.content = {};
            var w = storages.create("wordbook45qq_wordList_" + word.sdcard).get("list", []);
            for (let j in w)
                content[j] = w[j];
        }
    }
    return JSON.stringify(str);
}

function file45qq(dir, from) {
    var str = [];
    var jsFiles = files.listDir(dir, function(name) {
        let p = files.join(dir, name);
        if (name.endsWith(".45qq") && files.isFile(files.join(dir, name))) {
            let words = "";
            try {
                let j = JSON.parse(files.read(p));
                for (let i in j) {
                    words += i + "    ";
                }
            } catch (e) {}
            str.push({
                name: files.getNameWithoutExtension(p),
                path: p,
                content: words,
                from: from
            });
        }
        return false;
    });
    return str;
}

var workList = [];

inAndOut.in45qqFromPath = function(path) {
    let read, json;
    try {
        read = files.read(path);
    } catch (e) {
        toast("读取出错！请检查路径是否正确。");
        return false;
    }
    try {
        json = JSON.parse(read);
        for (let i in json) {
            let sd = addJs.addWork(inAndOut.getList(), i, json[i].summary);
            let storage = storages.create("wordbook45qq_wordList_" + sd);
            let childlist = storage.get("list", []);
            for (let j = 0;; j++) {
                let z = json[i].content[j];
                if (z == null)
                    break;
                childlist.push(z);
            }
            storage.put("list", childlist);
        }
    } catch (e) {
        log("解析解误：" + e);
        toast("导入失败！文件内容出错。");
        return false;
    }
    return true;
}

let inTextView = ui.inflate(
    <vertical padding="16 0">
        <text textColor="{{themeJs.text2}}">粘贴要导入的文本</text>
        <input id="text" gravity="top" textColor="{{themeJs.text}}" h="250"/>
        <text textColor="{{themeJs.text2}}">匹配规则</text>
        <input id="rape" textColor="{{themeJs.text}}" text="{word}  {mean}"/>
    </vertical>, null, false);

var inTextDialogs = dialogs.build({
    customView: inTextView,
    title: "导入文本",
    titleColor: themeJs.text,
    positive: "导入",
    neutral: "说明",
    negative: "取消",
    wrapInScrollView: false,
    autoDismiss: false
}).on("positive", (dialog) => {
    let rapr = getRaprArray(inTextView.rape.text());
    if (rapr.indexOf("{word}") != -1 || rapr.indexOf("{mean}") != -1) {
        let array = inTextView.text.text().split(/\n/);
        let comtent = getRaprComtent(rapr, array);
        
        if (comtent.length == 0)
            toast("匹配到内容为空！");
        else showComtent(comtent, (indices) => {
            let storage = storages.create("wordbook45qq_wordList_" + word_sd);
            let childlist = storage.get("list", []);
            let start = childlist.length;

            for (let i in indices) {
                let n = comtent[indices[i]];
                let word = n.word == null ? "" : n.word;
                let mean = n.mean == null ? "" : n.mean;
                addJs.addWord(childlist, word, mean, n.en, n.am, true);
            }
            storage.put("list", childlist);
            inTextView.text.setText("");
            dialog.dismiss();

            toastLog("导入完成！");

            if (rapr.indexOf("{en}") == -1 || rapr.indexOf("{am}") == -1) {
                toastLog("正在自动获取音标，请保持网络通畅！");

                threads.start(function() {
                    for (let i = start, l = childlist.length; i < l; i++) {
                        let item = childlist[i];
                        let ph = networkSourceJs.getPh(item.word);
                        if (item.en == null) item.en = ph.en;
                        if (item.am == null) item.am = ph.am;
                    }
                    storage.put("list", childlist);
                    toast("音标获取完成！");
                });
            }
        });
    } else toastLog("匹配规则必须包含{word}或{mean}其中一个！");
}).on("neutral", () => {
    showDescription(files.read("./description/inText.txt"));
}).on("negative", (dialog) => {
    dialog.dismiss();
});

inTextView.getParent().getParent().attr("bg", themeJs.layout);

function showDescription(description) {
    let descriptionDialog = dialogs.build({
        title: "导入说明",
        titleColor: themeJs.text,
        content: description,
        contentColor: themeJs.text2,
        negative: "返回",
        wrapInScrollView: false,
    })
    descriptionDialog.getView().attr("bg", themeJs.layout);
    descriptionDialog.show();
}

function showComtent(comtent, fun) {
    let show_array = getShowArray(comtent);
    let selectWordsDialogs = dialogs.build({
        title: "选择导入元素(" + comtent.length + ")",
        titleColor: themeJs.text,
        items: show_array[0],
        itemsColor: themeJs.text2,
        itemsSelectMode: "multi",
        itemsSelectedIndex: show_array[1],
        positive: "确定",
        negative: "取消",
        wrapInScrollView: false,
        autoDismiss: true
    }).on("multi_choice", (indices, items, dialog) => {
        fun(indices);
    });

    selectWordsDialogs.getView().attr("bg", themeJs.layout);

    selectWordsDialogs.show();
}

function getShowArray(array) {
    let a = [],
        b = [];
    for (let i in array) {
        let word = array[i]["word"];
        let mean = array[i]["mean"];
        let en = array[i]["en"];
        let am = array[i]["am"];
        a.push((word == null ? "" : word) + "  " +
            (en == null ? "" : "美[" + en + "]") + "  " +
            (am == null ? "" : "英[" + am + "]") +
            "\n" + (mean == null ? "" : mean));
        b.push(i);
    }
    return [a, b];
}

function getRaprArray(str) {
    let rapr = [];
    for (let i = 0, l = str.length, s = "", ss = ""; i < l; i++) {
        s = str[i];
        ss += s;
        if (i < l - 1) {
            if (str[i + 1] == "{" || s == "{") {
                if (s != "{") {
                    rapr.push(ss);
                    i++;
                }
                ss = "";
                for (let j = i; j < l; j++, i++) {
                    s = str[j];
                    ss += s;
                    if (s == "}") {
                        rapr.push(ss);
                        ss = "";
                        break;
                    }
                }
            }
        } else rapr.push(ss);
    }
    return rapr;
}

function getRaprComtent(rapr, array) {
    let comtent = [];
    for (let i = 0, l = array.length, rl = rapr.length, a = ""; i < l; i++) {
        a = array[i];
        let word = null;
        let currentContent;
        for (let j = 0, r = "", m = ""; j < rl; j++) {
            r = rapr[j];
            if (r.search(/{.+}/) != -1) {
                currentContent = r;
                m = getComtentForStr(a, j < rl - 1 ? rapr[j + 1] : null);
                if (m == null)
                    break;
                if (word == null)
                    word = {};
                word[r.slice(1, r.length - 1)] = m[0];
                if (m[1] == 1) {
                    if (i < l - 1) {
                        i++;
                        j++;
                        a = array[i];
                    } else break;
                } else a = m[1];
            } else {
                m = compareRemoreStr(a, r);
                if (m[0])
                    a = m[1];
                else break;
            }
        }
        if (word != null)
            comtent.push(word);
    }
    return comtent;
}

function compareStr(str1, str2, start) {
    if (start == null)
        start = 0;
    for (let i = 0, l1 = str1.length, l2 = str2.length; i < l2; i++) {
        if (l1 < l2 || str1[i + start] != str2[i])
            return false;
    }
    return true;
}

function compareRemoreStr(str1, str2) {
    if (compareStr(str1, str2)) {
        return [true, str1.slice(str2.length, str1.length)]
    }
    return [false, str1]
}

function getComtentForStr(str1, str2) {
    if (str2 != null) {
        if (str2 == "\n") {
            return [str1, 1];
        }
        for (let i = 0, l = str1.length; i < l; i++) {
            if (compareStr(str1, str2, i + 1)) {
                return [str1.slice(0, i + 1), str1.slice(i + 1, l)];
            }
        }
        return;
    }
    return [str1, ""];
}

let word_sd = "";
inAndOut.inTextToWork = function(sdcards) {
    word_sd = sdcards;
    inTextDialogs.show();
}

inAndOut.in45qq = function(list) {
    inAndOut.getList = function() {
        return list;
    };
    workList.splice(0, workList.length);
    workList = file45qq("/sdcard/Android/data/com.tencent.mobileqq/Tencent/QQfile_recv/", "QQ");
    workList.push.apply(workList, file45qq("/sdcard/Android/data/com.tencent.mm/MicroMsg/Download/", "微信"));
    workList.push.apply(workList, file45qq("/sdcard/简单词本/export/", "简单词本"));
    if (workList.length == 0)
        inView.prompt.setVisibility(View.VISIBLE);
    else inView.prompt.setVisibility(View.GONE);
    inView.workList.setDataSource(workList);
    inDialogs.show();
}

inAndOut.out45qq = function(list) {
    workList.splice(0, workList.length);
    selectView.name.setText("");
    for (let i in list) {
        workList.push({
            title: list[i].title,
            summary: list[i].summary,
            sdcard: list[i].sdcard,
            done: false,
        });
    }
    selectView.workList.setDataSource(workList);
    outDialogs.show();
}

module.exports = inAndOut;